/**
 * 资源查看
 */
var resourceMap = {};
var localStorageManagers = require('script/localStorageManagers.js');
var downloadUtils = require('scripts/Core/DownLoadUtil.js');
var mobileFrame=require('scripts/Core/MobileFrame.js');
(function($) {
	mui.init({
		swipeBack: false //启用右滑关闭功能
	});
	FastClick.attach(document.body);
	$.plusReady(function() {
		var self = plus.webview.currentWebview(); //课程页面传值
		var courseid = self.courseid;
		var catalogid=self.catalogid;
		if (courseid == null) mui.toast('传递的课程id为空');
		document.getElementById('fCourseid').value = courseid;
		document.getElementById('fCatalogid').value = catalogid;
		loadResource(); //课程页面传值
		//loadNotes(); //加载笔记
		//plus.downloader.enumerate(function(tasks){
		//console.log("当前下载任务数量:"+tasks.length);
		// });
	});
	//点击资源查看
	mui('#catalogs-div').on('tap', '.res-div', resView);
	//下载资源
	mui("#catalogs-div").on('tap', '.uploadres', uploadResource);
	//设置屏幕高度
	autoWidthHeight();
	//切换页签
	document.getElementById('slider').addEventListener('slide', function(e) {
		if (e.detail.slideNumber == 0) { //资源

		} else if (e.detail.slideNumber == 1) { //笔记

		} else if (e.detail.slideNumber == 2) { //提问

		}
	});
	document.addEventListener("pause", function () {
	   pauseVideo();
      //console.log("应用从前台切换到后台");
    }, false);
    document.addEventListener("resume", function () {
       //playVideo();
      // console.log("应用从后台切换到前台");
    }, false);
	//mui('header').on('tap','#opennoteview',openNoteview);
	//var downloadItems=publicUtils.getDownloadResourceSession();
	//alert(JSON.stringify(downloadItems));
})(mui);
//其他应用打开
			    mui('#viewres').on('tap','#viewtip1 .c2',function(){
			    	var respath=this.getAttribute("respath");
			    	respath=downloadUtils.getLocalAbsoluteUrl2(respath);//打开文件需要相对路径
			    	console.log(respath);
			    	var suffix=respath.substring(respath.lastIndexOf('.')+1,respath.length);
			    	if(respath.indexOf('http:')>=0){
			    	 //mui.toast('请先下载到本地');
			    	plus.runtime.openURL(respath, {}, function ( e ) {
			                  plus.nativeUI.alert( "无法打开'"+suffix+"'格式的文件,请安装相关应用." );
		             } );
		            }else{
		             plus.runtime.openFile(respath, {}, function ( e ) {
			                  plus.nativeUI.alert( "无法打开'"+suffix+"'格式的文件,请安装相关应用。" );
		             } );	
		            }
			    });
//拖拽
var isHiddenSlider = false;
//设置高度自适应
function autoWidthHeight() {
	var clienth = document.documentElement.clientHeight;
	var titleh = document.getElementsByClassName('mui-bar-nav')[0].offsetHeight;
	var videoh = document.getElementsByClassName('mui-content-view')[0].offsetHeight;
	var contentsdiv = document.getElementsByClassName('mui-control-content');
	var temph = clienth - titleh - videoh;
	for (var i = 0; i < contentsdiv.length; i++) {
		contentsdiv[i].style.minHeight = temph - 40 + 'px';
	}
}
//显示资源列表
var currResourceids=''; //已有资源
var resourceList= new Array();
/**
 * 加载资源，有网就远程加载，没网加载本地
 */
function loadResource() {
	currResourceids = ''; //已有资源
	resourceList = new Array();
	var isNet=hasNet();
	if(!isNet)loadResourcerLocal();
	if(isNet)loadResourceAjax();
}
//是否有网
function hasNet(){
	var isNet=mobileFrame.IsNetWorkCanUse();
	return isNet;
}
//本地加载
function loadResourcerLocal() {
	var courseid = document.getElementById('fCourseid').value;
	//显示本地缓存资源
	var resourceListJson = localStorageManagers.getResourcelistSession(courseid);
	if (resourceListJson != null && resourceListJson != undefined) {
		resourceList = resourceListJson;
		buildResourceDivs(resourceListJson, false);
	}
};
//ajax加载
function loadResourceAjax() {
	var courseid = document.getElementById('fCourseid').value;
	var userid = localStorageManagers.getUseridSession();
	var catalogid=document.getElementById('fCatalogid').value;
	var url=serverAjax + 'mobile/course/getResourcesByCourseid.do';
	if(catalogid>0)url=serverAjax + 'mobile/course/getResourcesBySelfCourseid.do';
	mui.ajax(url, {
		data: {
			userid: userid,
			currResourceids: currResourceids,
			courseid: courseid,
			catalogid:catalogid
		},
		dataType: 'json', //服务器返回json格式数据
		type: 'post', //HTTP请求类型
		timeout: 15000, //超时时间设置为10秒；
		success: function(data) {
			if (data.length == 0) return;
			//
			//var catalogid=document.getElementById('fCatalogid').value;
			//if(catalogid>0){
			//	var dataTemp=new Array();
			//	for(var i=0;i<data.length;i++){
			//		if(data[i].catalogId==catalogid)dataTemp.push(data[i]);
			//	}
			//	data=dataTemp;
			//}
			buildResourceDivs(data, true);
			//mui.toast("data"+data.length);
			localStorageManagers.setResourcelistSession(courseid, resourceList);
		},
		error: function(xhr, type, errorThrown) {
			console.log(xhr);
			ajaxErrorTip();
		}
	});
};

//构建资源列表,ifAjax:是否是从ajax加载
function buildResourceDivs(resList, ifAjax) {
	for (var i = 0; i < resList.length; i++) {
		var res = resList[i];
		if (!ifAjax) currResourceids += res.resId + ",";
		if (ifAjax) resourceList.push(res); //ajax加载的内容需要添加到缓存
		buildResourceDiv(res);
		var reskey=buildResKey(1,res.catalogId,res.resId);
		resourceMap[reskey] = res; //将资源数据存入map
	}
	if (currResourceids.length > 0) currResourceids = currResourceids.substring(0, currResourceids.length - 1);
}

//构建资源列表
function buildResourceDiv(res) {
	//var fResid=document.getElementById('fResid').value;
	//if(fResid==''||fResid==0){
	//	document.getElementById('fCatalogid').value = res.catalogId;
	//	document.getElementById('fCatalogname').value = res.catalogName;
	//	document.getElementById('fResid').value = res.resId;
	//	document.getElementById('fResname').value=res.title;
	//	document.getElementById('fRescatname').value = res.resCatName;
	//	loadQuestions();
	//}
	var catalogid = res.catalogId;
	var courseid = res.courseId;
	//课题div是否在
	var catalogdiv = document.getElementById("catalog-div" + catalogid);
	var restitle = res.title;
	if (restitle != null && restitle.length > 8) restitle = restitle.substring(0, 8) + '...';
	var status = getInitBtnStatus(res.catalogId, res.resId);
	var btnStatusText = getBtnViewtext(status);
	var catClass = getCatClass(res.resCatName);
	var resviewtype=resViewType(res.resPath);
	var  display='display:none';
	if(resviewtype=='文档'||resviewtype=='图片'||resviewtype=='三维'||resviewtype=='PDF')display='display:block;';
	if (catalogdiv == null) {
		var catalogdivs = document.getElementById('catalogs-div');
		var catalogname=res.catalogName;
		if (catalogname != null && catalogname.length > 10) catalogname = catalogname.substring(0, 10) + '...';
		var catalogdiv = '<div class="catalog-div" id="catalog-div' + catalogid + '"><div class="catalog-name"><p>' + catalogname + '</p></div>' + '<div class="catalog-ress" id="catalog-ress' + catalogid + '"><div class="res-div" courseid="' + courseid + '" catalogid="' + catalogid + '" catalogname="'+res.catalogName+'" resid="' + res.resId + '" resname="'+res.title+'" restype="' + res.resType + '" respath="' + res.resPath + '" rescatname="' + res.resCatName + '">' + '<span class="restype-div ' + catClass + '">' + res.resCatName + '</span><span class="resname-div">' + restitle + '</span><span class="download-div uploadres" catalogid="' + catalogid + '"  resid="' + res.resId + '" restype="' + res.resType + '" respath="' + res.resPath + '" status="' + status + '" style="'+display+'">' + btnStatusText + '</span>' + '</div></div></div>';
		catalogdivs.innerHTML = catalogdivs.innerHTML + catalogdiv;
	} else {
		var catalogressdiv = document.getElementById("catalog-ress" + catalogid);
		catalogressdiv.innerHTML = catalogressdiv.innerHTML + '<div class="res-div" courseid="' + courseid + '"  catalogid="' + catalogid + '" catalogname="'+res.catalogName+'" resid="' + res.resId + '" resname="'+res.title+'" restype="' + res.resType + '" respath="' + res.resPath + '" rescatname="' + res.resCatName + '"><span class="restype-div ' + catClass + '">' + res.resCatName + '</span><span class="resname-div">' + restitle + '</span><span class="download-div uploadres" catalogid="' + catalogid + '" resid="' + res.resId + '" restype="' + res.resType + '" respath="' + res.resPath + '" status="' + status + '" style="'+display+'">' + btnStatusText + '</span></div>';
	}
}
//下载完成设置状态
function downFinish(respath){
	
	var downdivs=document.getElementsByClassName('download-div uploadres');
	for(var i=0;i<downdivs.length;i++){
		//var dcatalogid=downdivs[i].getAttribute('resid');
		//var dresid=downdivs[i].getAttribute('resid');
		var drespath=downdivs[i].getAttribute('respath');
		if(respath==drespath)
			downdivs[i].innerHTML='<p class="status2">已缓存</p>';
		}
}
function getCatClass(preName) {
	var preClass = 'xt';
	switch (preName) {
		case "视频":
			preClass = 'sp';
			break;
		case "讲义":
			preClass = 'jy';
			break;
		case "习题":
			preClass = 'xt';
			break;
		case "教案":
			preClass = 'jy';
			break;
		case "随堂检测":
			preClass = 'stjc';
			break;
		default:
			preClass = 'xt';

	}
	return preClass;
}
//初始化资源列表时，获取按钮状态
function getInitBtnStatus(catalogid, resid) {
	//mui.toast(catalogid+','+resid);
	var key=buildResKey(1,catalogid,resid);
	var status = localStorageManagers.downloadResourceStatus(key);
	return status;
}
//查看资源
//各种不同资源分别处理
function resView() {
	var resdivs=document.getElementsByClassName('res-div');
	for(var i=0;i<resdivs.length;i++){
		resdivs[i].className='res-div';
	}
	this.className='res-div cur';
	document.getElementById('viewres').innerHTML='<div id="viewtip"></div>';
	var courseid=this.getAttribute('courseid');
	var catalogid = this.getAttribute('catalogid');
	var catalogname=this.getAttribute('catalogname');
	var resid = this.getAttribute('resid');
	var resname = this.getAttribute('resname');
	var rescatname = this.getAttribute('rescatname');
	document.getElementById('fCatalogid').value = catalogid;
	document.getElementById('fCatalogname').value = catalogname;
	document.getElementById('fResid').value = resid;
	document.getElementById('fResname').value = resname;
	document.getElementById('fRescatname').value = rescatname;
	//加载笔记
	loadNotes();
	//加载问题信息
	//loadQuestions();
	var key=buildResKey(1,catalogid,resid);
	var res = resourceMap[key];
	var restype = res.resType;
	var respath = res.resPath;
	if(restype!=3&&restype!=4)pauseVideo();
	//获得本地缓存路径，没有缓存则使用网络路径
	var localpath = downloadUtils.getLocalAbsoluteUrl(respath);
	if (localpath != null) respath = localpath;
	//MP4,MP3
	if(respath.endWith('.mp3')||respath.endWith('.mp4')){
		console.log('播放路径：' + respath);
		var videostr = '<video id="myVideo" controls="controls" style="width:100%;height:99%;background-color:black"  autoplay="autoplay" poster="../images/video_bg.jpg" src="' + respath + '">' + '<object  type="application/x-shockwave-flash" data="myvideo.swf"><param name="movie" value="myvideo.swf" />' + '<param name="flashvars" value="autostart=true&amp;file=myvideo.swf" /></object>' + '当前手机不支持 video直接播放，点击这里下载视频： <a href="myvideo.webm">下载视频</a></video>';
		document.getElementById('viewres').innerHTML = videostr;
		document.getElementById('myVideo').play();
		mui.toast('视频正在加载');
	}else if(restype==5&&rescatname=='教案'){
		openViewTextPage(res);
	}else{
		//修改为在本页显示查看按钮
		openEmptyPage(res);
	}
	
	//if (restype == 1 || restype == 6) {
		//文本及附件下载
	//	openEmptyPage(res);
		//document.getElementById('viewres').innerHTML="<div id='viewtip'>该资源不能直接查看，请下载</div>";
	//} else if (restype == 2) {
		//图片
	//	openEmptyPage(res);
		//document.getElementById('viewres').backgroundImage = respath;
	//} else if (restype == 3 || restype == 4) {
		//if(respath.indexOf('.mp3')!=-1||respath.indexOf('.mp4')!=-1){
		//视频，音频  #2E2E2E
	//	console.log('播放路径：' + respath);
	//	var videostr = '<video id="myVideo" controls="controls" style="width:100%;height:99%;background-color:black"  autoplay="autoplay" poster="../images/video_bg.jpg" src="' + respath + '">' + '<object  type="application/x-shockwave-flash" data="myvideo.swf"><param name="movie" value="myvideo.swf" />' + '<param name="flashvars" value="autostart=true&amp;file=myvideo.swf" /></object>' + '当前手机不支持 video直接播放，点击这里下载视频： <a href="myvideo.webm">下载视频</a></video>';
	//	document.getElementById('viewres').innerHTML = videostr;
	//	document.getElementById('myVideo').play();
		//document.getElementById('viewres').innerHTML="<video src='"+respath+"' style='width:100%;height:100%;background-color:#2E2E2E' controls></video>";
       //}else{
       //	openEmptyPage(res);
       //}
	//} else if (restype == 5) {
		//html
	//	openViewTextPage(res);
		//document.getElementById('viewres').innerHTML=result.resContent;
	//} else if (restype == 7) {
		//随堂测试
	//	document.getElementById('viewres').innerHTML = "<div id='viewtip'>该资源不能直接查看，请下载</div>";
	//}
}
//下载资源
function uploadResource(e) {
	e.stopPropagation();
	if(!hasNet())return;
	var thisbtn = this;
	var catalogid=thisbtn.getAttribute('catalogid');
	var resid = thisbtn.getAttribute("resid");
	var key=buildResKey(1,catalogid,resid);
	var res = resourceMap[key];
	var restype = res.resType;
	var rescatname=res.resCatName;
	if (restype==5&&rescatname=='教案') {
		mui.toast('在线编辑的教案不能下载,请直接查看');
	} else {
		createDownload(thisbtn, res.resPath);
	}
}
// 创建下载任务 ,status:0未下载，1下载中，2已下载，3已暂停
function createDownload(thisbtn, respath) {

	var status = thisbtn.getAttribute("status");
	switch (status) {
		case '0':
			downloadFile(thisbtn, respath);
			setDownloadBtnStatus(thisbtn, 1);
			break;
		case '1':
		    //正在下载的任务清除
			setDownloadBtnStatus(thisbtn, 0);
			break;
		case '2':
			//已下载完成不处理
			break;
		case '3':
			setDownloadBtnStatus(thisbtn, 1);
			break;
		default:
			setDownloadBtnStatus(thisbtn, 0);
	}
	//plus.downloader.enumerate(function(tasks) {
		//alert( "Unfinished task count: " + tasks.length );
	//});
}
//设置按钮状态
function setDownloadBtnStatus(thisbtn, status) {
	thisbtn.setAttribute('status', status);
	var text = getBtnViewtext(status);
	thisbtn.innerHTML = text;
}
//
function getBtnViewtext(status) {
	var text = "<p class='status0'></p>";
	switch (status) {
		case 0:
			text = "<p class='status0'></p>";
			break;
		case 1:
			text = "<p class='status1'></p>";
			break;
		case 2:
			text = "<p class='status2'>已缓存</p>";
			break;
		case 3:
			text = "<p class='status3'>已暂停</p>";
	}
	return text;
}
//调用父页面方法下载资源
function downloadFile(thisbtn, src) {
	var issave=saveDownResinfo(thisbtn);
	if(!issave)return;
	//下载在课程页面进行
	var parentWebView = plus.webview.getWebviewById("synccourse/courseindex.html");
	parentWebView.evalJS("downloadResource('" + src + "')");
}
//记录下载资源缓存
function saveDownResinfo(thisbtn) {
	var catalogid=thisbtn.getAttribute('catalogid');
	var resid = thisbtn.getAttribute('resid');
	var key=buildResKey(1,catalogid,resid);
	var res = resourceMap[key];
	res.key=key;
	res.path=res.resPath;
	var issave=localStorageManagers.pushDownresourceSessionItem(res);
	//alert('courseid:'+courseid+",coursename:"+coursename+",catalogid:"+catalogid+",catalogname:"+catalogname+",resid:"+resid+",resname:"+resname);
	return issave;
}
//打开不能查看的页面
function openViewTextPage(res) {
	var courseid = document.getElementById('fCourseid').value;
	var catalogid=document.getElementById('fCatalogid').value;
	var catalogname=document.getElementById('fCatalogname').value;
	var resid=document.getElementById('fResid').value;
	var resname=document.getElementById('fResname').value;
	var rescatname=document.getElementById('fRescatname').value;
	mui.openWindow({
		url: 'viewText.html',
		id: 'selfcourseview/viewText',
		styles:getStyles(),
		extras: {
			'courseid':courseid,
			'catalogid':catalogid,
			'catalogname':catalogname,
			'rescatname':rescatname,
			'resid': res.resId,
			'resname': res.title,
			'respath': res.resPath
		}
	});
}
//打开不能查看的页面
function openEmptyPage(res) {
	document.getElementById('viewres').innerHTML='<div id="viewtip1"><div class="c1">该资源无法在线查看</div><div class="c2" respath="'+res.resPath+'">其他应用打开</div></div>';
}
function openEmptyPage1(res) {
	var courseid = document.getElementById('fCourseid').value;
	var catalogid=document.getElementById('fCatalogid').value;
	var catalogname=document.getElementById('fCatalogname').value;
	var resid=document.getElementById('fResid').value;
	var resname=document.getElementById('fResname').value;
	var rescatname=document.getElementById('fRescatname').value;
	mui.openWindow({
		url: 'viewEmptyPage.html',
		id: 'selfcourseview/viewEmptyPage',
		styles:getStyles(),
		extras: {
			'courseid':courseid,
			'catalogid':catalogid,
			'catalogname':catalogname,
			'rescatname':rescatname,
			'resid': res.resId,
			'resname': res.title,
			'respath': res.resPath
		}
	});
};
//视频暂停
function pauseVideo(){
	var video=document.getElementById('myVideo');
	if(video!=null){
		//mui.toast("暂停");
		//var myVideo = document.getElementsByTagName('video')[0];
		//myVideo.pause();
		document.getElementById("myVideo").pause();
	}
};
//视频开始
function playVideo(){
	var video=document.getElementById('myVideo');
	if(video!=null){
		//mui.toast("暂停");
		//var myVideo = document.getElementsByTagName('video')[0];
		//myVideo.pause();
		document.getElementById("myVideo").play();
	}
};
